package com.bpmn.flow.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.bpmn.api.BpmTaskCallbackReqDTO;
import com.bpmn.flow.controller.form.ModelMetaInfoForm;
import com.bpmn.utils.ModelUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;

/**
 * BPM任务回调助手类
 * 用于统一构建BpmTaskCallbackReqDTO对象和处理回调业务逻辑
 *
 * @author wangzongrun
 */
@Slf4j
public class BpmTaskCallbackHelper {

    /**
     * 构造回调请求参数
     */
    public static BpmTaskCallbackReqDTO buildCallbackRequestDTO(Task task, FlowableEngineEntityEvent event, ProcessInstance processInstance) {
        BpmTaskCallbackReqDTO taskCallbackReqDTO = new BpmTaskCallbackReqDTO();
        taskCallbackReqDTO.setTaskId(task.getId());
        taskCallbackReqDTO.setTaskName(task.getName());
        taskCallbackReqDTO.setTaskDefinitionKey(task.getTaskDefinitionKey());
        taskCallbackReqDTO.setEventName(event.getType().name());
        taskCallbackReqDTO.setProcessInstanceId(task.getProcessInstanceId());
        taskCallbackReqDTO.setProcessDefinitionKey(processInstance.getProcessDefinitionKey());
        taskCallbackReqDTO.setBusinessKey(processInstance.getBusinessKey());
        taskCallbackReqDTO.setStartUserName(processInstance.getStartUserId());
        return taskCallbackReqDTO;
    }

    /**
     * 处理任务完成回调
     *
     * @param task            任务对象
     * @param event           流程事件
     * @param processInstance 流程实例
     */
    public static void handleTaskCompletedCallback(Task task, FlowableEngineEntityEvent event, ProcessInstance processInstance) {
        ModelMetaInfoForm metaInfo = ModelUtils.getCallbackUrl(task.getProcessDefinitionId());
        String taskCallbackUrl = metaInfo.getTaskCallbackUrl();
        if (StrUtil.isNotBlank(taskCallbackUrl)) {
            //构造回调请求参数
            BpmTaskCallbackReqDTO taskCallbackReqDTO = buildCallbackRequestDTO(task, event, processInstance);
            String jsonStr = JSONUtil.toJsonStr(taskCallbackReqDTO);
            try (HttpResponse response = HttpRequest.post(taskCallbackUrl).body(jsonStr).execute()) {
                log.info("处理回调成功: {}", response.body());
            } catch (Exception e) {
                log.error("处理回调失败", e);
            }
        }
    }
}